﻿using AutoMapper;
using BackData;
using Domain;
using Infratructure;
using MediatR;
using System.Net.Sockets;
using System.Transactions;
using Team.API.Applocation.Command.Quality;
using Yitter.IdGenerator;

namespace Team.API.Applocation.Hanldler.Quality
{
    public class CreateQualityHandler : IRequestHandler<CreateQualityCommand, APIResult<int>>
    {
        private readonly IRepository<Qualitymodel> _qualiRep;
        private readonly IMapper _mapper;
        private readonly IRepository<Nlogmodel> nlogRep;
        private readonly ILogger<CreateQualityHandler> logger;

        /// <summary>
        /// 初始化质检工单创建处理器
        /// </summary>
        /// <param name="qualiRep">质检模型仓储</param>
        /// <param name="mapper">AutoMapper 实例</param>
        public CreateQualityHandler(IRepository<Qualitymodel> qualiRep, IMapper mapper,IRepository<Nlogmodel> nlogRep,ILogger<CreateQualityHandler> logger)
        {
            _qualiRep = qualiRep;
            _mapper = mapper;
            this.nlogRep = nlogRep;
            this.logger = logger;
        }
        public async Task<APIResult<int>> Handle(CreateQualityCommand request, CancellationToken cancellationToken)
        {
                // 1. 命令请求映射为实体模型
                var qualityModel = _mapper.Map<List<Qualitymodel>>(request.qualityDtos);
            long id = 0;
            foreach (var item in qualityModel)
            {
                item.Id=YitIdHelper.NextId();
                item.Createtime=DateTime.Now;
                item.Updatetime=DateTime.Now;
                item.Reportingtime=DateTime.Now;
                item.IsDel=false;
                id = item.Id;
            }

            // 3. 执行仓储操作，添加质检工单
            var r =  0;

                // 4. 记录操作日志
                var logModel = new Nlogmodel
                {
                    Id= YitIdHelper.NextId(),
                    Message = "创建质检工单",
                    Category = "Quality",
                    Otherkey =id,
                    Operatingtime = DateTime.Now,
                    Operator = request.RealName
                };

            var r1 = 0; // 假设日志也通过同仓储管理

            using (TransactionScope tran = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                try
                {
                    logger.LogInformation($"{request.RealName}在{DateTime.Now}进行了此操作");
                    foreach (var item in qualityModel)
                    {
                        r=  await _qualiRep.AddAsync(item);
                    }
                    r1 = await nlogRep.AddAsync(logModel);
                    tran.Complete();
                }
                catch (Exception ex)
                {
                    logger.LogError("事务执行失败，发生回滚"+ex.Message);
                    throw;
                }
            }
               
            if(r1>0)
            {
                return new APIResult<int>
                {
                    Code = StateCode.OK,
                    Message = "质检工单创建成功",
                    Result = r
                };
            }
            else
            {
                return new APIResult<int>
                {
                    Code = StateCode.Fail,
                    Message = "质检工单创建失败",
                    Result = r
                };
            }
        }
    }
}
